<!--
 * @Descripttion: searchForm搜索条件查询
 * @Author: xp
 * @Date: 2022-09-02 22:05:29
-->
<template>
  <div class="search-form mb16">
    <div class="search-box">
      <el-row
        :style="{display: 'flex', alignItems: 'center', flexWrap: 'wrap', overflow: 'hidden' }"
        :class="[{ 'showMoreSearchItem': transitionShow }, 'oneLineSearchItem']"
      >
        <template v-for="(item, index) in formInputData">
          <el-col
            :span="item.span || (((item.typeCode === 'datePickerRange') || (item.typeCode === 'datePickerRangeI')) ? 12 : 8)"
            :key="index"
            class="search-wrapper mb16"
          >
            <b-form-item v-if="item.typeCode === 'input'" :title="item.title">
              <el-input
                style="flex: 1;"
                v-model="form[item.name]"
                :placeholder="item.placeholder || ('请输入'+item.title)"
                clearable
                @input="handleInput(item)"
                @keyup.enter.native="handleSearch"
                :disabled="item.disabled || false"
                :maxlength="item.maxlength || 30"
              />
            </b-form-item>
            <!-- 多个输入框展示 -->
            <b-form-item v-if="item.typeCode === 'manyInput'" :title="item.title" style="height:40px;" >
              <el-input
                style="flex: 1;"
                v-model="form[item.start]"
                :placeholder="item.placeholder || ('请输入'+item.title)"
                clearable
                @input="handleInput(item)"
                @keyup.enter.native="handleSearch"
                :disabled="item.disabled || false"
                :maxlength="item.maxlength || 30"
              />
              <div style="margin:0 5px;">~</div>
              <el-input
                style="flex:1;"
                v-model="form[item.end]"
                :placeholder="item.placeholder || ('请输入'+item.title)"
                clearable
                @input="handleInput(item)"
                @keyup.enter.native="handleSearch"
              />
            </b-form-item>
            <b-form-item v-if="item.typeCode === 'select'" :title="item.title">
              <el-select
                :disabled="item.disabled || false"
                v-model="form[item.name]"
                :placeholder="item.placeholder || ('请选择'+item.title)"
                style="flex: 1;"
                :multiple="item.multiple||false"
                clearable
                :filterable="item.filterable||false"
                @keydown.enter.native="handleSearch('select'+item.name)"
                @change="e => item.btnClick && item.btnClick(e)"
                :ref="'select'+item.name"
              >
                <el-option
                  v-for="t in item.optionData"
                  :key="t[item.kname] || t.key"
                  :value="t[item.kname] || t.key"
                  :label="t[item.vname] || t.value"
                >{{ t[item.vname] || t.value }}</el-option>
              </el-select>
            </b-form-item>
            <b-form-item v-if="item.typeCode === 'selectFilter'" :title="item.title">
              <el-select
                :disabled="item.disabled || false"
                v-model="form[item.name]"
                :placeholder="item.placeholder || ('请选择'+item.title)"
                style="flex: 1;"
                remote
                :remote-method="e => remoteMethod(e, item)"
                :multiple="item.multiple||false"
                clearable
                filterable
                :ref="'selectFilter'+item.name"
              >
                  <el-option
                    v-for="t in item.optionData"
                    :key="t[item.kname] || t.id"
                    :value="t[item.kname] || t.id"
                    :label="t[item.vname] || t.value"
                  >{{ t[item.vname] || t.value }}</el-option>
              </el-select>
            </b-form-item>
            <b-form-item
              v-if="(item.typeCode === 'datePickerRange') || (item.typeCode === 'datePickerRangeI') || (item.typeCode === 'datePickerRangeDate')"
              :title="item.title"
            >
              <el-date-picker
                :disabled="item.disabled || false"
                style="flex: 1;"
                v-model="form[item.name]"
                type="datetimerange"
                :picker-options="item.options || {}"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
                align="right"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="e => handleDateTimeChange(e, item)"
                :default-time="(item.typeCode === 'datePickerRangeI') ? ['00:00:00', '23:59:59'] : []"
              ></el-date-picker>
            </b-form-item>
            <b-form-item v-if="(item.typeCode === 'cascader')" :title="item.title">
              <el-cascader
                v-model="form[item.name]"
                :options="item.optionData"
                style="width:100%"
                :disabled="item.disabled || false"
                :props="{
                  value: item.kname || 'value',
                  label: item.vname || 'label',
                  children: item.childName || 'children'
                }"
                @change="e => handleSelect(e, item)"
                clearable
              ></el-cascader>
            </b-form-item>
            <!-- 单选框 -->
            <b-form-item v-if="item.typeCode === 'radio'" :title="item.title" style="height:40px;">
              <el-radio-group
                v-model="form[item.name]"
                @change="e => item.btnClick && item.btnClick(e)"
                style="display:flex;"
                :disabled="item.disabled || false"
              >
                <el-radio
                  v-for="t in item.optionData"
                  :key="t[item.kname] || t.key"
                  :value="t[item.kname] || t.key"
                  :label="t[item.vname] || t.key"
                >{{ t[item.vname] || t.value }}</el-radio>
              </el-radio-group>
            </b-form-item>
            <!-- 搜索多选框 -->
            <b-form-item v-if="item.typeCode === 'checkbox'" :title="item.title" style="height:40px;" :placeholder="'请选择'+item.title">
              <el-checkbox-group
                v-model="form[item.name]"
                style="width: 100%; height:40px !important; overflow:hidden;"
                :disabled="item.disabled || false"
              >
                <el-checkbox v-for="t in item.optionData" :label="t.key" :key="t.key">{{t.value}}</el-checkbox>
              </el-checkbox-group>
            </b-form-item>
          </el-col>
        </template>
      </el-row>
      <div class="btns" v-if="!transitionShow">
        <b-button-new :text="cancelName" hollow @click="handleReset"></b-button-new>
        <b-button-new :text="confirmName" @click="handleSearch"></b-button-new>
        <slot name="btns" />
      </div>
    </div>
    <div class="btn-expand-search" v-if="transitionShow">
      <b-button-new :text="cancelName" hollow @click="handleReset"></b-button-new>
      <b-button-new :text="confirmName" @click="handleSearch"></b-button-new>
      <slot name="btns" />
    </div>
    <!-- 点击展开/收起 -->
    <div class="more-search fontTheme">
      <div class="line-before"></div>
      <div class="search-text" ref="searchText" @click="onTransition" v-if="formInputData.length > oneLineNumer">
        高级搜索
        <div :class="[transitionShow ? 'scale':'scale1']">
          <i class="el-icon-arrow-down"></i>
        </div>
      </div>
      <div class="line-after"></div>
    </div>

    <div v-if="isPopup && formInputData.length > 2" class="mb16">
      <div style="display: flex; align-items: center; justify-content: center;">
        <div @click="onTransition" class="exchange-search">
          <div style="display: inline-block; user-select: none;">{{transitionShow?'收起':'展开'}}</div>
          <div :class="[transitionShow ? 'scale':'scale1']">
            <i class="el-icon-arrow-down"></i>
          </div>
        </div>
        <b-button-new :text="confirmName" @click="handleSearch"></b-button-new>
        <b-button-new :text="cancelName" class="ml16" hollow @click="handleReset"></b-button-new>
        <slot name="btns" />
      </div>
    </div>
  </div>
</template>
  <script>
export default {
  name: "QueryForm",
  props: {
    data: {
      type: Array,
      default: () => []
    }, // 查询条件
    isPopup: {
      // 是否弹窗
      type: Boolean,
      default: () => false
    },
    isDefaultReset: {
      // 是否自动重置
      type: Boolean,
      default: () => true
    },
    form: {
      type: Object,
      default: () => {}
    }, // 查询条件的form变量
    confirmName:{
      type:String,
      default: () => '查询'
    },
    cancelName:{
      type:String,
      default: () => '重置'
    },
  },
  data() {
    return {
      start: new Date(),
      end: new Date(),
      iViewDate: [],
      transitionShow: false, // 展开/收起
      datePickerOption: {},
    };
  },
  computed: {
    oneLineNumer() {
      let width = document.body.clientWidth;
      if (this.formInputData.length == 4 && this.formInputData.findIndex(item => item.span > 6) != -1) {
        return 3
      }
      return width <= 1440 ? 3 : 4
    },
    formInputData() {
      let width = document.body.clientWidth;
      this.data.map((item, index) => {
        // 把下拉option的key 转换成字符串 防止key为0 选中时值为undefined
        if (item.typeCode == 'select' && item.optionData && item.optionData.length > 0) {
          item.optionData.map(item1 => item1[item.kname || 'key'] = item1[item.kname || 'key'].toString())
        }
        if (item.typeCode == 'selectFilter') {
          item.optionData = []
        }
        Object.assign(item, {
          span: item.span ? item.span : width > 1440 ? 6 : 8,
          isHidden: index > (width > 1440 ? 4 : 3)
        })
      });
      return this.data
    }
  },
  mounted() {},
  methods: {
    // 判断要不要marginBottom
    hasMarginBottom(index) {
      let width = document.body.clientWidth;
      let num = 3;
      // >1920分辨率 - 显示一排4个  反之3个
      if (width > 1440) {
        num = 4;
      } else {
        num = 3;
      } 
      if (this.isPopup) {
        num = 2;
      }
      if (
        index >
        (parseInt(
          this.formInputData.length % num != 0
            ? this.formInputData.length / num + 1
            : this.formInputData.length / num
        ) -
          1) *
          num
      ) {
        return false;
      } else {
        return true;
      }
    },
    handleDateTimeChange(val, item) {
      if (!val) {
        this.$parent.$parent.dataForm.query[item.start] = "";
        this.$parent.$parent.dataForm.query[item.end] = "";
      } else {
        this.$parent.$parent.dataForm.query[item.start] = val[0];
        this.$parent.$parent.dataForm.query[item.end] = val[1];
      }
    },
    // 级联选中
    handleSelect(e, item) {
      console.log(e, item);
    },
    // input正则表达
    handleInput(item) {
      // 正则校验
      switch (item.type) {
        case "int":
          this.form[item.name] = this.form[item.name].replace(/\s*/g, "");
          if (isNaN(parseInt(this.form[item.name]))) {
            this.form[item.name] = "";
            return;
          }
          if (!this.$_regExp.integer1.test(this.form[item.name])) {
            this.form[item.name] = parseInt(this.form[item.name]);
          }
          break;
      }
    },
    // 是否显示下拉框
    isShowSelectOptions(isShowSelectOptions, name) {
      console.log(isShowSelectOptions, name, "---------- aaaa");
      if (!isShowSelectOptions) this.$refs[name].blur();
    },
    // 远程搜索方法
    remoteMethod(val, item) {
      let sendData = { page: 1, page_size: 10 }
      sendData[item.sname || item.vname] = val
      this.$api[item.jsName][item.fnName](sendData).then(res => {
        item.optionData = res.page_list || []
        this.$forceUpdate()
      })
    },
    // 搜索
    handleSearch(name) {
      if (name && this.$refs[name]) {
        // 拦截下拉搜索框 取消焦点
        this.$refs[name][0].blur();
      }
      const timeObj = {};
      const casObj = {};
      this.data.map(item => {
        if (
          (item.typeCode === "datePickerRange" ||
            item.typeCode === "datePickerRangeI") &&
          this.form[item.name]
        ) {
          timeObj[item.start] = this.timeFormatDate(this.form[item.name][0]);
          timeObj[item.end] = this.timeFormatDate(this.form[item.name][1]);
        }
        if (item.typeCode === "datePickerRangeDate" && this.form[item.name]) {
          // 年月日
          timeObj[item.start] = this.timeFormatDate(
            this.form[item.name][0]
          ).substring(0, 10);
          timeObj[item.end] = this.timeFormatDate(
            this.form[item.name][1]
          ).substring(0, 10);
        }
        // 级联  只管两级
        if (item.typeCode === "cascader") {
          let selectedItem = this.form[item.name];
          casObj[item.name] = selectedItem[1] || "";
        }

        // else if (item.typeCode === 'dateSectionViewDate' && this.form[item.name]) {
        //   timeObj[item.start] = this.timeFormatDate(this.form[item.name][0]).substring(0, 10);
        //   timeObj[item.end] = this.timeFormatDate(this.form[item.name][1]).substring(0, 10);
        // } else if (item.typeCode === 'dateSectionViewI' && this.form[item.name]) {
        //   timeObj[item.start] = this.timeFormatDate(this.form[item.name][0]);
        //   if (this.timeFormatDate(this.form[item.name][1]).slice(-8) === '00:00:00') {
        //     timeObj[item.end] = this.timeFormatDate(this.form[item.name][1]).replace(this.timeFormatDate(this.form[item.name][1]).substring(11, 19), '23:59:59');
        //   } else {
        //     timeObj[item.end] = this.timeFormatDate(this.form[item.name][1]);
        //   }
        // }
      });
      const form = { ...this.form, ...timeObj, ...casObj };
      this.$emit("search", form);
    },
    // 清除搜索条件
    handleReset() {
      this.data &&
        this.data.forEach(item => {
          if (
            [
              "datePickerRange",
              "datePickerRangeI",
              "datePickerRangeDate",
              "manyInput"
            ].includes(item.typeCode)
          ) {
            this.$set(this.$parent.$parent.dataForm.query, item.start, "");
            this.$set(this.$parent.$parent.dataForm.query, item.end, "");
            this.$set(this.$parent.$parent.dataForm.query, item.name, null);
          } else if (
            item.typeCode === "checkbox" ||
            (item.typeCode === "select" && item.multiple)
          ) {
            this.$set(this.form, item.name, []);
          } else {
            this.$set(this.form, item.name, "");
          }
        });
        if (this.confirmName !== '确认') {
          this.isDefaultReset && this.handleSearch();
        }
      this.$emit("reset");
    },
    timeFormatDate(time) {
      const date = new Date(time);
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
      let hh = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
      let mm =
        date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
      let ss =
        date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
      return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
    },
    onTransition() {
      this.transitionShow = !this.transitionShow;
      if (this.transitionShow) {
        this.data.map(item => (item.isHidden = false));
      } else {
        return this.data.map((item, index) =>
          Object.assign(item, { isHidden: index > 3 })
        );
      }
    }
    // /
    //   onBlurHandle(value, item) {
    //     item.onBlur && item.onBlur(value, item);
    //   },
  }
};
</script>
<style lang="scss" scoped>
.search-form{
  .search-box{
    display: flex;
    align-items: center;
  }
  ::v-deep.el-input .el-input__inner{
    padding-right: 15px;
  }
  ::v-deep.el-select{
    .el-input .el-input__inner{
      box-sizing: border-box;
      padding-right: 32px;
    }
  }
  .btn-expand-search{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .btns{
    display: inline-flex;
    align-items: center;
    justify-content: flex-end;
  }
  .search-wrapper{
    display: inline-block;
    padding-right: 24px;
  }
  .more-search{
    display: flex;
    width: 100%;
    margin-top: 16px;
    cursor: pointer;
    .search-text{
      width: 110px;
      font-size: 14px;
      line-height: 22px;
      text-align: center;
    }
    .line-before, .line-after{
      flex: 1;
      position: relative;
    }
    .line-before{
      &::before{
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        transform: (0, -50%);
        height: 1px;
        background: #EBEEF5;
        content: '';
      }
    }
    .line-after{
      &::after{
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        transform: (0, -50%);
        height: 1px;
        background: #EBEEF5;
        content: '';
      }
    }
  }
}
.exchange-search {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 10px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
  font-weight: 400;
}
.scale {
  display: inline-block;
  transform: rotate(-180deg);
  -webkit-transform: rotate(-180deg);
  transition: 0.5s;
  margin-left: 3px;
}
.scale1 {
  display: inline-block;
  transition: 0.5s;
  margin-left: 3px;
}
.showMoreSearchItem {
  height: auto !important;
  margin-right: -24px;
}
.oneLineSearchItem {
  flex: 1;
  height: 40px;
}
.show-more{
  margin-right: 16px;
  cursor: pointer;
  user-select: none;
  >.el-icon-arrow-down{
    margin-left: 4px;
  }
}
</style>
  <style lang="scss">
.form-item-wrapper {
  .el-select__tags {
    height: 40px !important;
    overflow: auto !important;
    & + div > input {
      height: 40px !important;
    }
  }
}
</style>